"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : gs_ctl stop 使用immediate方式在主机停止集群
Create At   : 2020/07/21
@zou_jialiang0505328126
Description :
    1. 执行TPCC
    2.执行TPCC过程中stop主机
    3.查询TPCC状态
    4.启动数据库
    5.查询数据库状态
    6.循环步骤1~5 100次
    7.执行TPCC，检查数据库是否可正常使用
Expect      :
    未改变原逻辑
History     :
    created： 2020/07/21  created by @wan005
    modified: 2020/09/16  modified by @wan005 DTS2020072904011问题修改
    modified: 2021/1/11 modified by @peilinqian 修改Constant实例化调用；
"""

import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

logger = Logger()
common = Common()


class StopImmediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    constant = Constant()
    TPCC_PATH = macro.TPCC_PATH
    TPCC_ERROR = Constant.TPCC_ERROR
    commsh = CommonSH()
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info('---Opengauss_Reliability_Dbsys_Case123.py start---')

    def test_stop_immediate(self):
        for i in range(1, 10):
            logger.info('-------------round ' + str(i) + ' -------------')
            logger.info("-----------start TPCC-----------")
            tpcc_thread = ComThread(common.startTPCC,
                                    args=(self.dbPrimaryRootNode,
                                          self.TPCC_PATH,
                                          f'. runBenchmark.sh'
                                          f' {macro.TPCC_PROPS_FILENAME}',))
            tpcc_thread.setDaemon(True)
            tpcc_thread.start()

            time.sleep(15)
            logger.info("-----------stop opengauss immediate-----------")
            stop_cmd = '''
                source {source_path};
                gs_ctl stop -D {DN1_PATH} -m immediate'''.format(
                source_path=self.DB_ENV_PATH, DN1_PATH=self.DB_INSTANCE_PATH)
            logger.info(stop_cmd)
            stop_msg = self.dbPrimaryUserNode.sh(stop_cmd).result()
            logger.info(stop_msg)
            self.assertTrue(
                stop_msg.find(self.constant.GS_CTL_STOP_SUCCESS_MSG) > -1)

            logger.info('---------------check TPCC status-------------------')
            tpcc_thread.join(int(macro.TPCC_RUN_MAX_TIME) * 2)
            tpcc_result = tpcc_thread.get_result()
            self.assertIn(self.TPCC_ERROR, tpcc_result)

            logger.info(
                '--------------------start opengauss-----------------------')
            start_cmd = '''
                source {source_path};
                gs_om -t start
                '''.format(source_path=self.DB_ENV_PATH)
            logger.info(start_cmd)
            start_msg = self.dbPrimaryUserNode.sh(start_cmd).result()
            logger.info(start_msg)
            self.assertTrue(
                start_msg.find(
                    self.constant.START_SUCCESS_MSG) > -1 or start_msg.find(
                    self.constant.START_DEGRADED_MSG) > -1)

            logger.info('--------------check opengauss status------------')
            check_cmd = '''
                source {source_path};
                gs_om -t status --detail'''.format(
                source_path=self.DB_ENV_PATH)
            logger.info(check_cmd)
            check_msg = self.dbPrimaryUserNode.sh(check_cmd).result()
            logger.info(check_msg)
            self.assertTrue(check_msg.find(self.constant.STANDBY_NORMAL) > -1)
            self.assertTrue(check_msg.find(self.constant.PRIMARY_NORMAL) > -1)

        logger.info('--------------------start TPCC-------------------------')
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, self.TPCC_PATH,
                                       f'. runBenchmark.sh '
                                       f'{macro.TPCC_PROPS_FILENAME}')
        logger.info('------------------循环外：tpcc_result------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find("ERROR") < 0)
        logger.info('-------------' + tpcc_result + '----------------------')

    def tearDown(self):
        logger.info('----------------this is tearDown----------------------')
        self.commsh.check_whether_remain_dirty_page()
        self.standby_1_sh.check_data_consistency()
        self.standby_2_sh.check_data_consistency()
